﻿
GridClass = function () {
    var self = this;

    function AutoPageSize() {
        alert(window.screen.height);
    }

    self.textFieldChange = function (field, trigger, index) {
        field.getTrigger(0).show();
    }
    self.searchFieldTriggerClick = function (field, trigger, index) {

        var me = field,
            store = me.up("grid").getStore();

        if (index === 0) {
            me.setValue('');
            store.clearFilter();
            trigger.hide();
        }
    };

    self.search = function (button) {
        var me = button,
            store = me.up("grid").getStore();

        var array = $(".SearchArea,.SearchArea input").serializeArray();
        var aoData = {};

        var form = button.up("grid").down("form").getForm();
        $(array).each(function () {
            if (aoData[this.name]) {
                if ($.isArray(aoData[this.name])) {
                    aoData[this.name].push(this.value);
                } else {
                    aoData[this.name] = [aoData[this.name], this.value];
                }

            } else {
                var field = form.findField(this.name);
                if (field && field.getXType() === "combo") {
                    aoData[this.name + '[]'] = form.findField(this.name).getValue();
                } else {
                    aoData[this.name] = this.value;
                }
            }
        });

        store.proxy.extraParams = aoData;
        store.reload();
    }

    self.autoFillextraParams = function (store, options) {
        //暂时停止试验
        var new_params = { name: store.ownerGrid.down("form").getValue() };
        Ext.apply(store.proxy.extraParams, new_params);
    }

    var onComboBoxSelect = function (combo) {
        var store = combo.up("gridpanel").getStore();

        store.pageSize = parseInt(combo.getValue(), 10);
        store.reload();
    };


    // 模块 Grid 点击
    self.OnModuleGridItemClick = function (view, record, item, index, e, options) {
        App.Main.G.CurrentDataRecordId = record.Id;
    }
    // 模块 Grid 双击
    self.OnModuleGridItemDblClick = function (view, record, item, index, e) {
        var grid = view.up("gridpanel") || view.up("treepanel");
        while (grid.ownerCt.getXType() === "grid") {
            grid = grid.ownerCt;
        }

        var toolbar = grid.down("toolbar");
        if (toolbar == null) {
            return;
        }
        var bs = toolbar.items;
        for (var i = 0; i < bs.getCount(); i++) {
            var b = bs.getAt(i);
            if (b.getText() === '浏览') {
                b.handler(b);
                return;
            }
        }
    }
    // 在新窗体中打开模块项
    self.OpenModuleItemWindow = function (button, action, params) {
        var grid = button.up("grid") || button.up("treepanel");

        var selected = (grid) ? grid.getSelectionModel().getSelection() : null;

        if (!params.ShowOnly && (selected) && selected.length === 0) {
            Tip("操作提示", "没有选中任何记录！");
            return;
        }
        var dataId = (selected && selected.length > 0) ? getPkValue(selected[0].getData()) : "";

        Ext.net.directRequest({
            cleanRequest: true,
            url: action + "/" + dataId,
            extraParams: params,
            method: "GET",
            control: this,
            eventMask: {
                showMask: true,
                msg: "正在打开..."
            }
        });
    }

    // 模块操作
    self.OnModuleOperation = function (button, action, params) {
        if (params == null) params = {};
        var grid = button.up("grid") || button.up("treepanel");
        // 处理等无窗体删除
        if (params.IsAjax) {
            var selected = grid.getSelectionModel().getSelection();
            if (!(selected)) return false;
            if (selected.length === 0) {
                Tip("操作提示", "没有选中任何记录！");
                return false;
            }

            Ext.MessageBox.confirm(button.getText() + '确认',
                '请确实是要' + button.getText() + '这些记录?',
                function (btn) {
                    if (btn === 'yes') {

                        params.Ids = generaterParamFromSelected(selected);

                        Ext.Ajax.request({
                            url: action,
                            params: params,
                            method: "POST",
                            success: function (response) {

                                var result = Ext.JSON.decode(response.responseText);

                                if (result.success) {
                                    if (result.msg.length > 0)
                                        Tip('提示', result.msg);
                                    grid.store.load();
                                } else {
                                    Tip('操作失败', result.errors);
                                }

                            }
                        });
                    }
                });
            return true;
        } else {
            self.OpenModuleItemWindow(button, action, params);
            return true;
        }
    }

    // 展示Item
    self.DoGridItemClick = function (grid, record, item, index) {
        // 联动
        var refreshs = grid.ownerCt.RefreshModule;
        if (refreshs) {
            //SaveState(grid.ownerCt.Info.root + '_' + grid.ownerCt.Info.id + '_ID', getPkValue(record), 'Guid',
            //    function (response) {
            //        for (var i = 0; i < refreshs.length; i++) {
            //            var g = Ext.getCmp(refreshs[i]);
            //            if ((g) && (g.store)) {
            //                g.store.reload({});
            //            }
            //        }
            //    });
        }
        var container = grid.ownerGrid.up("container");

        // 显示 Item 面板
        var p = container.down("panel[region='east']");
        if (p == null) {
            return;
        }
        if (!(container.tag)) {
            return;
        }

        p.loader = {
            scripts: true,
            autoLoad: false,
            url: container.tag.ItemPanelUrl,
            params: {
                cmd: "ItemPanel",
                containerId: p.getId(),
                Id: getPkValue(record.data),
                IsReadOnlyForm: false//true
            },
            failure: function () { alert("加载错误"); },
            //renderer: function (loader, response, active) {
            //    loader.getTarget().update(response.responseText, true);
            //    return true;
            //},
            listeners: {
                beforeload: function () {
                    this.target.body.mask('正在加载...');
                    p.items.removeAll();
                },
                load: function (loader) {
                    p.setVisible(true);

                    if (this.target.body)
                        this.target.body.unmask();
                }
            }
        }
        p.getLoader().load();
    }

    // 提示信息
    function Tip(title, content) {
        Ext.net.Notification.show({
            hideFx: {
                fxName: 'switchOff',
                args: [{}]
            },
            showFx: {
                fxName: 'slideIn',
                args: ['tl', { easing: 'bounceOut', duration: 1000 }]
            },
            pinEvent: 'click',
            alignToCfg: { offset: [20, 20], position: 'tc-tc' },
            html: content,
            title: title
        });
    }

    // 用选择的id构建Post参数对象
    function generaterParamFromSelected(selected) {

        var ids = new Array();

        for (var i = 0; i < selected.length; i++) {
            ids.push(getPkValue(selected[i].getData()));
        }

        return ids;
    }

    function getPkValue(record) {
        if (typeof (record) == "undefined") {
            return null;
        }
        if (record.Id) {
            return record.Id;
        } else if (record.ID) {
            return record.ID;
        } else {
            return record.id;
        }
    }

    //获取树的勾选值
    self.GetTreeValues = function (obj) {
        var ids = [];
        var tree;
        if (obj.getXType() === "button") {
            var p = obj.up("panel");
            tree = Ext.ComponentQuery.query('treepanel', p);
        } else {
            tree = obj;
        }
        Ext.Array.each(tree,
            function (item, index, allItems) {
                item.getChecked().forEach(function (node) {
                    if (node.raw)
                        ids.push(node.raw.id);
                });
            });

        return ids;
    }

    self.checkedChildNodes = function (node, checked, eOpts) {
        function ck(node) {
            Ext.Array.each(node.childNodes,
                function (item, index, allItems) {
                    item.set('checked', checked);
                    if (!item.isLeaf() && node.hasChildNodes())
                        ck(item);
                });
        }

        function rck(node) {
            var cnt = 0;
            Ext.Array.each(node.parentNode.childNodes,
                function (item, index, allItems) {
                    if (item.get('checked')) {
                        cnt += 1;
                    }
                });
            node.parentNode.set('checked', (cnt === node.parentNode.childNodes.length));
            if (!node.parentNode.isRoot()) rck(node.parentNode);
        }

        if (!node.isLeaf() && node.hasChildNodes()) {
            ck(node);
        }
        rck(node);
    }

    self.dropItem = function (node, data, overModel, dropPosition, options) {
        var ids = [];
        var parentId;
        if (dropPosition === "append") {
            parentId = overModel.raw.id;
            overModel.childNodes.forEach(function (item) {
                ids.push(item.raw.id);
            });
            ids.push(data.records[0].raw.id);
        } else {
            //虚拟根节点没有这个
            if (typeof (overModel.parentNode.raw) != "undefined") {
                parentId = overModel.parentNode.raw.id;
            } else {
                parentId = "";
            }
            overModel.parentNode.childNodes.forEach(function (item) {
                ids.push(item.raw.id);
            });
        }

        var url = data.view.ownerCt.tag.dropApiUrl;

        if (url != null && url.length === 0) {
            Tip('异常', "Api 地址获取不到。");
        }

        $.ajax({
            type: "POST",
            url: url,
            data: {
                'parentId': parentId,
                'ids': ids
            },
            success: function (result) {
                Tip('操作成功', result.msg);
            }
        });
    };
    self.beforedropItem = function (node, data, overModel, dropPosition, dropFunction) {

    };

    self.showSeaechArea = function (button, action, params) {

        var seaechArea = button.up("grid").query("toolbar")[1];
        seaechArea.setHidden(!seaechArea.getHidden());

    }

    self.findParamValue = function (gridId, fieldName) {
        var grid = Ext.getCmp(gridId);
        if (grid) {
            return grid.down("form").down("hidden[name='" + fieldName + "']").getValue();
        }


        alert("grid 未找到");
        console.log("App.Grid.findParamValue('dataList3aefb6153a7243ce849c1f8b30872b38','test')");
        return "";
    }

    self.Refresh = function (button) {
        var store = (button.up("grid") || button.up("treepanel")).getStore();

        store.reload();
    }
    self.refreshGrid = function (button) {
        var grid = button.up("grid") || button.up("treepanel");

        if (grid) return grid.getId();

        return "";
    }

    self.getSelectedIds = function (grid) {

        var rowSelectionModel = grid.getSelectionModel().getSelection();

        var ids = new Array();
        Ext.Array.each(rowSelectionModel,
            function (item, index) {
                ids.push(item.getData().Id);
            });


        return ids;
    }


    self.PostColumnConfig = function (cmd, c, params) {
        if (params == null) {
            params = {};
        }
        eval('params.cmd="' + cmd + '";');
        eval('params.column="' + c.dataIndex + '";');

        var g = c.up("grid") || c.up("treepanel");
        if (typeof (g.tag) == "undefined") {
            g = g.up("grid") || g.up("treepanel");//启用冻结列以后还得再向上查找。
        }
        eval('params.moduleid="' + g.tag.ModuleId + '";');
        if (g.tag.root)
            eval('params.root="' + g.tag.root + '";');

        $.post('/api/Config/SaveCustomColumn', params,
            function (result) {
                if (result.errors.length>0)
                    Tip('提示', result.errors);
                else
                    Tip('提示', result.msg);
            },
            "json");
    }
    // 显示列
    self.ShowColumn = function (ct, c) {
        self.PostColumnConfig('Show', c);
    }
    // 隐藏列
    self.HideColumn = function (ct, c) {
        self.PostColumnConfig('Hide', c);
    }
    // 移动列


    //ct        : Ext.grid.header.Container。The grid's header Container which encapsulates all column headers.
    //column    : Ext.grid.column.Column。The Column header Component which provides the column definition
    //fromIdx   : Number
    //toIdx     : Number
    //eOpts     : Object
    self.MoveColumn = function (ct, column, fromIdx, toIdx, eOpts) {
        var index = toIdx;

        Ext.each(ct.items.items,
            function (item) {
                if (item.dataIndex == '') {
                    index = index - 1;
                }
            });


        self.PostColumnConfig('Move', column, { index: index });
    }
    // 调整列宽度
    self.ResizeColumn = function (ct, c, w) {
        if (c.cellWidth == undefined || c.cellWidth === w || c.flex) {
            return;
        } else {
            self.PostColumnConfig('Resize', c, { width: w });
        }
    }
    // 改变列排序
    self.ChangeSort = function (ct, c, d) {
        self.PostColumnConfig('Sort', c, { sort: d });
    }
}